//
//  UIScrollView+otherDelegate.m
//  KSBridgeDesign
//
//  Created by huzhaoke on 2021/4/17.
//

#import "UIScrollView+otherDelegate.h"
#import <objc/runtime.h>
#import "HKScrollViewDelegateProxy.h"

@interface UIScrollView()

@property (nonatomic, strong) HKScrollViewDelegateProxy *delegateProxy;

@end

@implementation UIScrollView (otherDelegate)

+ (void)load {
    [self swizzleSelector:@selector(setSwizzleDelegate:) oriSelector:@selector(setDelegate:)];
}

+ (void)swizzleSelector:(SEL)swizzleSelector oriSelector:(SEL)oriSelector {
    Class cls = [self class];
    Method oriMethod = class_getInstanceMethod(cls, oriSelector);
    Method swizzleMethod = class_getInstanceMethod(cls, swizzleSelector);
    BOOL didAddMethod = class_addMethod(cls, oriSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzleSelector, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    } else {
        method_exchangeImplementations(oriMethod, swizzleMethod);
    }
}

- (void)setSwizzleDelegate:(id)delegate {
    if (self.delegateProxy ) {
        if (self.delegateProxy != delegate) {
            self.delegateProxy.delegate = delegate;
        }
        [self setSwizzleDelegate:self.delegateProxy];
    } else {
        [self setSwizzleDelegate:delegate];
    }
}

- (void)setOtherDelegate:(id<UIScrollViewDelegate>)otherDelegate {
    if (!self.delegateProxy) {
        self.delegateProxy = [HKScrollViewDelegateProxy alloc];
        self.delegateProxy.delegate = self.delegate;
    }
    self.delegateProxy.otherDelegate = otherDelegate;
    self.delegate = self.delegateProxy;
}

- (id<UIScrollViewDelegate>)otherDelegate {
    return self.delegateProxy.otherDelegate;
}

- (void)setDelegateProxy:(HKScrollViewDelegateProxy *)delegateProxy {
    objc_setAssociatedObject(self, @selector(delegateProxy), delegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (HKScrollViewDelegateProxy *)delegateProxy {
    return objc_getAssociatedObject(self, @selector(delegateProxy));
}

@end
